// 引入koa-router
const Router = require('koa2-router');
const router = new Router();

const { timeTrans } = require("../../utils");
const {
  getUsers,
  addUsers,
  updateUsers,
  deleteUsers,
} = require("../../model/admin/users");

/* users增删改查 */

// 查找users
router.get("/", async function (ctx) {
  ctx.body = await getUsers();
});

// 添加users
router.post("/add", (ctx) => {
  // console.log("----------------users请求---------------", req.body);
  const users_id = Number(ctx.request.body.users_id);
  let { username, password, nickname } = ctx.request.body;
  let role = nickname === "管理员" ? 2 : 3;
  const ctime = timeTrans(ctx.request.body.ctime);
  // console.log(users_id, username, password, nickname, role, ctime);
  // return;
  addUsers([users_id, username, password, nickname, role, ctime])
    .then(() => {
      ctx.body = {
        code: 200,
        msg: "添加用户成功",
      };
    })
    .catch((err) => {
      ctx.body = {
        code: 500,
        msg: "添加用户失败",
        err,
      };
    });
});

// 修改users
router.post("/update", (ctx) => {
  const users_id = Number(ctx.request.body.users_id);
  let { username, password, nickname } = ctx.request.body;
  let role = nickname === "管理员" ? 2 : 3;
  const utime = timeTrans(ctx.request.body.utime);
  // console.log(users_id, username, password, nickname, role, utime);
  // return;
  updateUsers([username, password, nickname, role, utime, users_id])
    .then(() => {
      ctx.body = {
        code: 200,
        msg: "修改用户成功",
      };
    })
    .catch((err) => {
      ctx.body = {
        code: 500,
        msg: "修改用户失败",
        err,
      };
    });
});

// 删除users
router.get("/delete", (ctx) => {
  const users_id = Number(ctx.request.query.users_id);
  deleteUsers([users_id])
    .then(() => {
      ctx.body = {
        code: 200,
        msg: "删除用户成功",
      };
    })
    .catch((err) => {
      ctx.body = {
        code: 500,
        msg: "删除用户失败",
      };
    });
});

module.exports = router;
